/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { cleanDocumentTitle } from '@base/utils';
import { useMutationObserver } from 'ahooks';
import React, { useEffect, useState } from 'react';

/**
 *
 * @description 清空页面标题
 */
export function useCleanDocumentTitle() {
  useMutationObserver(cleanDocumentTitle, document.querySelector('title'), { childList: true });
}

interface DOMRectExtend extends DOMRect {
  parentTop?: number;
}

/**
 *
 * @descriptions 监听元素获取bound
 * @param ref
 * @returns
 */
export function useObserverBoundingClientRect(
  ref: React.MutableRefObject<HTMLDivElement | undefined>,
): DOMRectExtend {
  const [bound, setBound] = useState<DOMRectExtend>({} as DOMRectExtend);

  const trigger = () => {
    const target = ref.current;
    if (target) {
      const parent = target.parentNode as HTMLDivElement;
      const parentTop = parent ? parent.offsetTop : 0;
      const b = target.getBoundingClientRect() as DOMRectExtend;
      b.parentTop = parentTop;
      setBound(b);
    }
  };

  useMutationObserver(trigger, ref.current, {
    childList: true,
    subtree: true,
  });

  useEffect(() => {
    trigger();
  }, [ref]);

  return bound;
}
